package com.yijietong.yiliao.doctor.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.yijietong.yiliao.doctor.pojo.BaseBean;
import com.yijietong.yiliao.doctor.pojo.User;
import com.yijietong.yiliao.doctor.pojo.UserToken;
import com.yijietong.yiliao.doctor.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * 功能详细描述
 *
 * @author 奇奇
 * @version create at 2017-11-13  17:51
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private IUserService userService;

    private Gson gson = new Gson();

    //执行Handler方法之前执行
    //用于身份认证、身份授权
    //比如身份认证，如果认证通过表示当前用户没有登陆，需要此方法拦截不再向下执行
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
            throws Exception {
        //获取请求的url
//        String url = httpServletRequest.getRequestURI();
        //判断url是否是公开地址(实际使用时将公开地址配置到配置文件中)
//        if (url.indexOf("login") >= 0 || url.indexOf("register") >= 0) {
//            //如果要进行登录提交，放行
//            return true;
//        }

//        获取body的JSON串
//        BufferedReader br = new BufferedReader(new InputStreamReader(httpServletRequest.getInputStream(), "utf-8"));
//        StringBuffer sb = new StringBuffer("");
//        String temp;
//        while ((temp = br.readLine()) != null) {
//            sb.append(temp);
//        }
//        br.close();
//        String params = sb.toString();
//        Token tokenBean = gson.fromJson(params, Token.class);
//        String token = tokenBean.token;

        // 获取参数中的token.
        String token = httpServletRequest.getParameter("token");
        if(token!=null) {
            UserToken userToken = userService.getTokenCreateByToken(token);
            if(userToken==null) {
                userToken = new UserToken();
            }
            long tempMillis = System.currentTimeMillis() - userToken.getCreated();
            if (userToken.getCreated() == 0 || tempMillis < 0f || tempMillis > 2592000000f) {
                // 如果毫秒值大于1个月2592000000，则提示登录超时
                //将实体对象转换为JSON Object转换
                BaseBean baseBean = new BaseBean();
                baseBean.setCode(11);
                baseBean.setMessage("登录超时，请重新登录。");
                String json = gson.toJson(baseBean);
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json; charset=utf-8");
                PrintWriter out = null;
                close(out,httpServletResponse,json);
                return false;
            }
            return true;
        } else {
            BaseBean baseBean = new BaseBean();
            baseBean.setCode(12);
            baseBean.setMessage("缺少token");
            String json = gson.toJson(baseBean);
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            close(out,httpServletResponse,json);
            return false;
        }

        //return false表示拦截，不向下执行
        //return true表示放行
    }

    private void close(PrintWriter out,HttpServletResponse httpServletResponse,String json){
        try {
            out = httpServletResponse.getWriter();
            out.append(json);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    //进入Handler方法之后，返回modelAndView之前执行
    //应用场景从modelAndView出发：将公用的模型数据(比如菜单导航)在这里
    //传到视图，也可以在这里统一指定视图
    // 暂时还不了解是啥意思，先留着不动。
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("HandlerInterceptor1......postHandle");
    }

    //执行Handler完成执行此方法
    //应用场景：统一异常处理，统一日志处理
    // 暂时还不了解是啥意思，先留着不动。
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
        System.out.println("HandlerInterceptor1......afterHandle");
    }


    class Token{
        String token;
    }
}
